package com.easy.work.go

import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel

class MainActivity : FlutterActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
  }

  override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
    super.configureFlutterEngine(flutterEngine)
    MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "android/action")
      .setMethodCallHandler { call, result ->
        when (call.method) {
          "launch" -> {
            try {
              val url = call.arguments<String>() ?: ""
              val intent: Intent = if (url.startsWith("intent://")) {
                Intent.parseUri(url, Intent.URI_INTENT_SCHEME)
              } else {
                Intent(Intent.ACTION_VIEW, Uri.parse(url))
              }
              startActivity(intent)
              result.success(true)
            } catch (e: Exception) {
              if (e is ActivityNotFoundException) {
                result.error("error_not_found", e.stackTraceToString(), null)
              } else {
                result.error("error", e.stackTraceToString(), null)
              }
            }
          }

          "settings" -> {
            val name = call.arguments<String>() ?: ""
            val value = Settings.Global.getInt(contentResolver, name, 0)
            result.success(value)
          }

        }
      }

  }
}
